package com.aofeng.hybrid.orm;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by LGY on 2016-07-04.
 */
public class JSonMapConverter {

    public static Map<String, Object> toMap(JSONObject object) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();

        // null对象转换成空map
        if (object == null) {
            return map;
        }

        Iterator<String> iter = object.keys();
        while (iter.hasNext()) {
            String key = iter.next();
            Object value = null;
            try {
                value = object.get(key);
            } catch (JSONException e) {
                throw new RuntimeException("数据错误，key: " + key, e);
            }

            if (value instanceof JSONArray) {
                // 把JSON集合转换成List
                List<Map<String, Object>> set = saveList((JSONArray) value);
                map.put(key, set);
            } else if (value instanceof JSONObject) {
                Map<String, Object> set = toMap((JSONObject) value);
                map.put(key, set);
            } else {
                map.put(key, value);
            }
        }

        return map;
    }

    private static List<Map<String, Object>> saveList(JSONArray array)
            throws Exception {
        List<Map<String, Object>> set = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = (JSONObject) array.get(i);
            Map<String, Object> map = toMap(obj);
            set.add(map);
        }
        return set;
    }

}
